package gen.tools.deploy;

import gen.tools.Widgets;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SwitchHTTPservice extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public SwitchHTTPservice() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		response.setCharacterEncoding(wid.UIcodeSet);
		response.setContentType("application/text");
		
		final int depmainSN = Integer.parseInt( request.getParameter("depmainSN") );
		final String actType = request.getParameter("actType");	//看是 stop還是 start
		final String subsysId = request.getParameter("subsysId");
		final String envId = request.getParameter("envId");
		final String squadId = request.getParameter("squadId");
		final String hostIP = request.getParameter("hostIP");	//欲操作的主機
		final int port = Integer.parseInt( request.getParameter("port") );
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		String res = ""; 
		
		InputStream in = null;
		Channel channel = null;
		Session session = null;
		try {
			final int fdepdetailid = wid.getfDepdetailid(depmainSN);	//取得細項ID
			conn = wid.getConn();
			
			String sql = "INSERT INTO fdepdetail (depmainSN,fdepdetailid,fDepActTypeId,hostIP,squadId,bDT,envId) VALUES(?,?,?,?,?,?,?)";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, depmainSN);
			ps.setInt(2, fdepdetailid);
			ps.setInt(3, "stop".equalsIgnoreCase(actType)?3:7);		// 3關閉Server Group下轄主機HTTPD, 7開啟Server Group下轄主機HTTPD
			ps.setString(4, hostIP);
			ps.setString(5, squadId);
			ps.setTimestamp(6, wid.cDT());
			ps.setString(7, envId);
			ps.execute();
			
			//查詢主機OS登入的帳密
			sql = "SELECT loginId,loginPWD FROM hosts WHERE subsysId=? AND ip=? AND port=?";
			ps = conn.prepareStatement(sql);
			ps.setString(1,subsysId);
			ps.setString(2, hostIP);
			ps.setInt(3, port);
			rs = ps.executeQuery();
			rs.next();
			final String usrId = rs.getString("loginId");
			final String usrPwd = rs.getString("loginPWD");
			
			final String status = wid.chkServiceStatus(hostIP, usrId, usrPwd);
			boolean isNeedPerform = false;
			
			if( "stop".equalsIgnoreCase(actType) ) {
				if( status.contains("httpd (pid") ) {
					isNeedPerform = true;
				}
			} else {
				if( status.contains("is stopped")) {
					isNeedPerform = true;
				}
			}
			
			if( isNeedPerform ) {
				final JSch jsch = new JSch();
				final Properties config = new java.util.Properties();
				
				config.put("StrictHostKeyChecking", "no");
				
				session = jsch.getSession(usrId, hostIP, 22);
				session.setConfig(config);
				session.setPassword(usrPwd);
				session.connect();
				
				channel = session.openChannel("exec");
				
				String cmd = "";
				
				if ("root".equalsIgnoreCase(usrId)) {
					cmd = "service httpd "+actType;
				} else {
					cmd = "sudo service httpd "+actType;
				}
				
				((ChannelExec) channel).setCommand( cmd );

				channel.setInputStream(null);

				((ChannelExec) channel).setErrStream(System.err);

				in = channel.getInputStream();

				channel.connect();

				final byte[] tmp = new byte[1024];
				while (true) {
					while (in.available() > 0) {
						int i = in.read(tmp, 0, 1024);
						if (i < 0)
							break;
						res += new String(tmp, 0, i);
						//System.out.print(new String(tmp, 0, i));
					}
					if (channel.isClosed()) {
						break;
					}
					try {
						Thread.sleep(1000);
					} catch (Exception ee) {
					}
				}
				channel.disconnect();
				session.disconnect();
				
				if( res.contains("OK") ) {
					res = "OK";
				} else {
					res = "FAIL";
				}
			} else {
				if( "stop".equalsIgnoreCase(actType) ) {
					res="原本就未啟動";	
				} else {
					res="原本居然沒停止";
				}
			}
			
			sql = "UPDATE fdepdetail SET eDT=?,depResult=? WHERE depmainSN=? AND fdepdetailid=?";
			ps = conn.prepareStatement(sql);
			ps.setTimestamp(1, wid.cDT() );
			ps.setString(2, wid.chkServiceStatus(hostIP, usrId, usrPwd) );
			ps.setInt(3, depmainSN);
			ps.setInt(4, fdepdetailid);
			ps.execute();
		} catch (Exception e) {
			wid.errLog(e);
		} finally {
			try {
				if ( rs !=null ) { rs.close(); }
				if ( ps !=null ) { ps.close(); }
				if ( conn !=null ) { conn.close(); }	
			} catch(Exception e) { e.printStackTrace(); }
			if ( in != null) { in.close(); }
			if ( channel != null ) { if ( channel.isConnected() ) { channel.disconnect(); } }
			if ( session != null ) { if ( session.isConnected() ) { session.disconnect(); } }
		}
		response.getWriter().write(res);
	}

}
